<%@ page import="java.util.Map" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.tianxiabuyi.persist.QBuilder" %>
<%@ page import="com.tianxiabuyi.utils.Tools" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.tianxiabuyi.utils.JSONUtil" %>
<%@ page import="com.tianxiabuyi.persist.Where" %>
<%@ page import="com.alibaba.fastjson.TypeReference" %>
<%@ page import="javax.persistence.criteria.CriteriaBuilder" %>
<%@ page import="static sun.misc.MessageUtils.where" %>
<%@ page import="com.xiaomi.xmpush.server.*" %>
<%@ page import="com.tianxiabuyi.Message" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ page import="org.apache.http.client.HttpClient" %>
<%@ page import="org.apache.http.impl.client.DefaultHttpClient" %>
<%@ page import="org.apache.http.client.methods.HttpPost" %>
<%@ page import="org.apache.http.entity.mime.content.StringBody" %>
<%@ page import="org.apache.http.entity.mime.content.FileBody" %>
<%@ page import="org.apache.http.entity.mime.MultipartEntity" %>
<%@ page import="org.apache.http.HttpResponse" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="com.tianxiabuyi.model.utils.PushUtil" %>
<%@ page import="com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_OUTPeer" %>
<%@ page import="org.jsoup.Jsoup" %>
<%@ page import="org.jsoup.select.Elements" %>
<%@ page import="org.jsoup.nodes.Entities" %>
<%--
  Created by IntelliJ IDEA.
  User: tianwn
  Date: 2017/6/7
  Time: 16:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="UTF-8"%>
<%!
    private static final String  APP_SECRET_KEY = "ZjjaqXl9xws1O/VXdZ25Mw==";
    private static final String PACKAGE_NAME = "com.tianxiabuyi.hospital";

    /**
     *  @Param hospital     医院code
     *  @Param pages        页数
     *  @Definition         通知记录展示
     */
    public Message messgaeList (Input input) {
        Map msgOutMap = new HashMap();
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", -999);
        Integer pages = input.getInt("pages", 1);
        Map<Integer, Integer> hasReadMap = new HashMap<Integer, Integer> ();
        Map<Integer, Integer> noReadMap = new HashMap<Integer, Integer> ();
        Map<Integer, Integer> commentMap = new HashMap<Integer, Integer>();
        List<Map> list =  QBuilder.db("basedb").select("new map(hno.id as id, hno.title as title, hno.isComment as comment, hnc.name as category_name, hnl.name as level_name, hno.author as author)").from("HospitalNotice as hno, HospitalNoticeCategory as hnc, HospitalNoticeLevel as hnl")
                .where(new Where("hno.category = hnc.id").and("hno.level = hnl.id").and("hno.hospital =", hospital).and("hno.status = ", STATUS_ENABLE))
                .page(10, pages).order("hno.id", "desc").query().getResultObj();
        StringBuffer sb = new StringBuffer("-999,");
        StringBuffer commentSb = new StringBuffer("-999,");
        for (Map noticeMap : list) {
            Integer nid = Tools.getInt(noticeMap.get("id") + "", 0);
            Integer comment = Tools.getInt(noticeMap.get("comment") + "", 0);
            if (comment.equals(1)) {
                commentSb.append(nid + "").append(",");
                commentMap.put(nid, 0);
            } else {
                noticeMap.put("comment", "无需评论");
            }
            sb.append(nid + "").append(",");
            hasReadMap.put(nid, 0);
            noReadMap.put(nid, 0);
        }
        String idIndex = (sb.toString()).substring(0, (sb.toString()).length() - 1);
        String commentIndex = (commentSb.toString()).substring(0, (commentSb.toString()).length() - 1);
        List<Map> feedBackList = QBuilder.db("basedb").queryHql("select new map(readTime as read_time, noticeId as notice_id) from HospitalNoticeFeedback where noticeId in (" + idIndex +  ")");
        for (Map feedBackMap : feedBackList) {
            String feedStatus = Tools.getDesc(feedBackMap.get("read_time") + "", "");
            Integer noticeId = Tools.getInt(feedBackMap.get("notice_id") + "", 0);
            if (feedStatus.equals("")) {
                noReadMap.put(noticeId, Tools.getInt(noReadMap.get(noticeId) + "", 0) + 1);
            } else {
                hasReadMap.put(noticeId, Tools.getInt(hasReadMap.get(noticeId) + "", 0) + 1);
            }
        }
        List<Map> commentBackList = QBuilder.db("basedb").queryHql("select new map(hnc.noticeId as notice_id, hu.id as id) from HospitalNoticeComment as hnc, hospital_user as hu where hnc.noticeId in (" + commentIndex + ") and hnc.hospital = " + hospital + "and hnc.status = " + STATUS_ENABLE + "and hnc.userId = hu.id");
        for(Map commentBackMap : commentBackList) {
            Integer noticeId = Tools.getInt(commentBackMap.get("notice_id") + "", 0);
            commentMap.put(noticeId, Tools.getInt(commentMap.get(noticeId) + "", 0) + 1);
        }
        for(Map noticeMap : list) {
            Integer nid = Tools.getInt(noticeMap.get("id") + "", 0);
            noticeMap.put("has_read", hasReadMap.get(nid) + "");
            noticeMap.put("no_read", noReadMap.get(nid) + "");
            if (null != commentMap.get(nid)) {
                noticeMap.put("comment", Tools.getInt(commentMap.get(nid) + "", 0) + "");
            }
        }
        msgOutMap.put("list", list);
        msgOutMap.put("count", pageCount(input));
        msg.put("data", msgOutMap);
        return msg;
    }


    /**
     *  @Param hospital     医院code
     *  @Param page_number  页数
     *  @Definition         具体含有多少页
     */
    public int pageCount(Input input) {
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", 0);
        List<String> countStringList = QBuilder.db("basedb").queryHql("select concat(id, '') from HospitalNotice where hospital = " + hospital + "and status = " + STATUS_ENABLE);
        Integer count = Tools.getInt(countStringList.size() + "", 0);
        Integer page_count = 0;
        if ((count % 10) == 0) {
            page_count = count / 10;
            page_count = page_count.equals(0)?1:page_count;
        } else {
            page_count = count / 10 + 1;
        }
        return page_count;
    }

    /**
     *  @Param hospital     医院code
     *  @Param page         页数
     *  @Definition         级别内容
     */
    public Message levelListContent(Input input) {
        Map dataOutMap = new HashMap();
        Message msg = new Message();
        Integer hospital = input.getInt("hospital", 0);
        Integer page = input.getInt("page", 0);
        List<String> countLevelList = QBuilder.db("basedb").queryHql("select concat(id, '') from HospitalNoticeLevel where hospital = " + hospital + "and status = " + STATUS_ENABLE);
        Integer count = Tools.getInt(countLevelList.size() + "", 0);
        Integer page_count = 0;
        if ((count % 10) == 0) {
            page_count = count / 10;
            page_count = page_count.equals(0)?1:page_count;
        } else {
            page_count = count / 10 + 1;
        }
        List<Map> levelList = QBuilder.db("basedb").select("new map (hnl.jsonString as json, hnl.name as name, hnl.id as id)").from("HospitalNoticeLevel as hnl").
                              where(new Where("hnl.hospital = ", hospital).and("hnl.status = ", STATUS_ENABLE))
                            .page(10, page).order("hnl.id", "desc").query().getResultObj();
        for(Map levelMap : levelList) {
            String levelJson = Tools.getDesc(levelMap.get("json") + "", "{}");
            Map levelDetailMap = JSONUtil.mapFromJson(levelJson);
            levelMap.put("condition", Tools.getDesc(levelDetailMap.get("condition") + "", ""));
            levelMap.put("color", Tools.getDesc(levelDetailMap.get("color") + "", ""));
            levelMap.remove("json");
        }
        dataOutMap.put("list", levelList);
        dataOutMap.put("pages", page_count + "");
        msg.put("data", dataOutMap);
        return msg;
    }

    /**
     *  @Param id   等级ID
     *  @Definition 删除等级
     */
    public Message deleteLevel (Input input) {
        Message msg = new Message();
        Integer id = input.getInt("id", 0);
        int hangshu = QBuilder.db("basedb").execHQL("update HospitalNoticeLevel set status = 0 where id = " + id + "and status = " + STATUS_ENABLE);
        if (hangshu == 0) {
            msg.setErrcodeAndErrmsg(30041, "修改失败");
            return msg;
        }
        return msg;
    }

    /**
     * @Param operator_id   操作人ID
     * @Param operator_name 操作人姓名
     * @Param hospital      医院CODE
     * @Param name          等级名字
     * @Param condition     内容
     * @Param color         颜色
     * @Definition          添加等级
     */
     public Message addLevel(Input input) {
         Message msg = new Message();
         HospitalNoticeLevel hospitalNoticeLevel = JSONUtil.fromJson(JSONUtil.toJson(input.getParameters()), HospitalNoticeLevel.class);
         hospitalNoticeLevel.setJson("condition", input.getDesc("condition", ""));
         hospitalNoticeLevel.setJson("color", input.getDesc("color", ""));
         List<String> idList = QBuilder.db("basedb").queryHql("select concat(id, '') from HospitalNoticeLevel where name = '" + input.getDesc("name", "") + "' and hospital = " + input.getInt("hospital", -999) + "and status = " + STATUS_ENABLE);
         if (idList.size() != 0) {
             msg.setErrcodeAndErrmsg(30041, "此等级已添加，请勿重新添加");
             return msg;
         }
         Integer addId = (Integer) DBTools.db("basedb").addItem(hospitalNoticeLevel);
         if (null == addId) {
             msg.setErrcodeAndErrmsg(30041, "等级添加失败");
             return msg;
         }
         return msg;
     }

     /**
      * @Param id        通知发送ID
      * @Param hospital  医院CODE
      * @Definition      通知发送详情
      */
     public Message messageDetail(Input input) {
         Message msg = new Message();
         Integer id = input.getInt("id", 0);
         Integer hospital = input.getInt("hospital", 0);
         List<Map> detailList = QBuilder.db("basedb").select("new map(hno.title as title, hno.author as author, hno.receiver as receiver, hno.cTime as create_time, hno.content as content, hnc.name as category_name, hnl.name as level_name)")
                                .from("HospitalNotice as hno, HospitalNoticeCategory as hnc, HospitalNoticeLevel as hnl")
                                .where(new Where("hno.id = ", id).and("hno.hospital = ", hospital).and("hno.category = hnc.id").and("hno.level = hnl.id")).page(1, 1).query().getResultObj();
         if (detailList.size() == 0) {
            msg.setErrcodeAndErrmsg(30041, "无具体信息");
            return msg;
         }
         Map detailMap = detailList.get(0);
         detailMap.put("has_read", 0);
         detailMap.put("no_read", 0);
         List<Map> feedBackList = QBuilder.db("basedb").queryHql("select new map(readTime as read_time) from HospitalNoticeFeedback where noticeId = " + id);
         for(Map feedBackMap : feedBackList) {
             String feedStatus = Tools.getDesc(feedBackMap.get("read_time") + "", "");
             if (feedStatus.equals("")) {
                 detailMap.put("no_read", Tools.getInt(detailMap.get("no_read") + "", 0) + 1);
             } else {
                 detailMap.put("has_read", Tools.getInt(detailMap.get("has_read") + "", 0) + 1);
             }
         }
         Date sendDate = new Date(Tools.getLong(detailMap.get("create_time") + "", 0L));
         detailMap.put("date", DateUtil.formatDateByFormat(sendDate, "yyyy-MM-dd HH:mm:ss"));
         msg.put("data", detailMap);
         return msg;
     }

     /**
      * @Param id       通知发送ID
      * @Param hospital 医院CODE
      * @Definition     评论人详情
      */
      public Message commentList (Input input) {
          Message msg = new Message();
          Map outMap = new HashMap();
          Integer id = input.getInt("id", 0);
          Integer hospital = input.getInt("hospital", 0);
          List<Map> commentList = QBuilder.db("basedb").select("new map(hnc.content as content, hnc.time as time, hnc.cTime as create_time, hus.name as comment_name, hnc.userId as user_id, dept.deptName as dept_name, hnc.cTime as create_time, hnc.atId as at_id)").
                               from("HospitalNoticeComment as hnc, hospital_user as hus, Dept as dept, hospital_dept_user as hdept").
                               where(new Where("hnc.noticeId = ", id).and("hnc.hospital = ", hospital).and("hnc.userId = hus.id").and("hnc.userId = hdept.user_id").and("hdept.dept_id = dept.id"))
                               .query().getResultObj();
          int commentSize = commentList.size();
          StringBuffer sb = new StringBuffer("-999,");
          Map<Integer, String> atNameMap = new HashMap<Integer, String> ();
          for(Map commentMap : commentList) {
              Integer atId = Tools.getInt(commentMap.get("at_id") + "", 0);
              sb.append(atId + "").append(",");
          }
          String atIds = (sb.toString()).substring(0, (sb.toString()).length() - 1);
          List<Map> atNameList = QBuilder.db("basedb").queryHql("select new map(id as id, name as name) from hospital_user where id in (" + atIds + ")");

          for(Map atMap : atNameList) {
              Integer atId = Tools.getInt(atMap.get("id") + "", 0);
              String name = Tools.getDesc(atMap.get("name") + "", "");
              atNameMap.put(atId, name);
          }

          for(Map commentMap : commentList) {
              Integer atId = Tools.getInt(commentMap.get("at_id") + "", 0);
              if (null != atNameMap.get(atId)) {
                  commentMap.put("content", "@" + Tools.getDesc(atNameMap.get(atId) + "", "") + " " + Tools.getDesc(commentMap.get("content") + "", ""));
              }
          }
          outMap.put("size", commentSize + "");
          outMap.put("list", commentList);
          msg.put("data", outMap);
          return msg;
      }

      /**
       * @Param hospital 医院CODE
       * @Param id       通知发送ID
       * @Definition     未反馈人名单
       */
      public Message noReadList (Input input) {
          Map outMap = new HashMap();
          Message msg = new Message();
          Integer hospital = input.getInt("hospital", 0);
          Integer id = input.getInt("id", 0);
          Integer pages = input.getInt("pages", 0);
          List<Map> detailList = QBuilder.db("basedb").select("new map(hnc.name as category_name, hnl.name as level_name) ").
                                 from("HospitalNotice as hno, HospitalNoticeCategory as hnc, HospitalNoticeLevel as hnl").
                                 where(new Where("hno.id = ", id).and("hno.hospital = ", hospital).and("hno.category = hnc.id").and("hno.level = hnl.id")).
                                  page(1, 1).query().getResultObj();
          if (detailList.size() == 0) {
              msg.setErrcodeAndErrmsg(30041, "无详细信息");
              return msg;
          }
          Map detailMap = detailList.get(0);
          String categoryName = Tools.getDesc(detailMap.get("category_name") + "", "");
          String levelName = Tools.getDesc(detailMap.get("level_name") + "", "");
          List<Map> noReadList = QBuilder.db("basedb").select("new map(hnu.id as id, hnu.name as name, hnu.employee_id as employee_id, hnu.phone as phone, '" + categoryName + "' as category_name, '" + levelName + "' as level_name) ").from("HospitalNoticeFeedback as hnf, hospital_user as hnu").
                                 where(new Where("hnf.noticeId = ", id).and("hnf.hospital = ", hospital).and("hnf.userId = hnu.id").and("hnf.readTime is null")).page(10, pages).order("hnu.id", "desc").query().getResultObj();

          outMap.put("list", noReadList);
          outMap.put("pages", noReadPages(input) + "");
          msg.put("data", outMap);
          return msg;
      }

        /**
         *
         * @param input
         * @return   int 页数
         */
        public int noReadPages(Input input) {
            Integer id = input.getInt("id", 0);
            Integer hospital = input.getInt("hospital", 0);
            List<Map> noReadList = QBuilder.db("basedb").select("new map(id as id)").from("HospitalNoticeFeedback as hnf").where(new Where("hnf.noticeId = ", id).and("hnf.hospital = ", hospital)
                                    .and("hnf.readTime is null"))
                                   .query().getResultObj();
            Integer pageNumbers = noReadList.size();
            Integer page_count = 0;
            if ((pageNumbers % 10) == 0) {
                page_count = pageNumbers / 10;
                page_count = page_count.equals(0)?1:page_count;
            } else {
                page_count = pageNumbers / 10 + 1;
            }
            return page_count;
        }

      /**
       * @Param hospital 医院CODE
       * @Definition     类型list
       */
      public Message categoryList (Input input) {
          Message msg = new Message();
          Integer hospital = input.getInt("hospital", 0);
          hospital = 0;
          List<Map> cateList = QBuilder.db("basedb").queryHql("select new map(name as name, id as id) from HospitalNoticeCategory where hospital = " + hospital + "and status = " + STATUS_ENABLE);
          msg.put("data", cateList);
          return msg;
      }

      /**
       * @Param hospital 医院CODE
       * @Definition     级别list
       */
      public Message levelList (Input input) {
          Message msg = new Message();
          Integer hospital = input.getInt("hospital", 0);
          List<Map> levelList = QBuilder.db("basedb").queryHql("select new map(name as name, id as id) from HospitalNoticeLevel where hospital = " + hospital + "and status = " + STATUS_ENABLE);
          msg.put("data", levelList);
          return msg;
      }

       /**
         * @Param hospital 医院CODE
         * @Definition 通知发送获取所有直系标签
         */
       public Message tagAllList(Input input){
            Message msg = new Message();
            Integer hospital = input.getInt("hospital",-999);
            List<Map> tagList = QBuilder.db("basedb").select("new map(id as id,name as name,alias as alias)").from("hospital_label").where(new Where("hospital=",hospital).and("status=",STATUS_ENABLE)).query().getResultObj();
            msg.put("data",tagList);
            return msg;
       }

       /**
        * @Param hospital 医院CODE
        * @Param title    标题
        * @Param content  内容
        * @Param category 类型id
        * @Param level    等级id
        * @Param is_comment    是否可评论（1是，0否）
        * @Param author        发送人
        * @Param receiver      发送范围
        * @Param img           图片JSO
        * @Param attachment    附件名
        * @Param operator_id   操作人ID
        * @Param operator_name 操作人姓名
        * @Param from          发送端标志，web或app
        * @return          客户端通知发送
        */
        public Message noticeCreate(Input input) throws UnsupportedEncodingException{
            Message msg = new Message();
            Integer hospital = input.getInt("hospital", 0);
            String title = input.getDesc("title", "");
            String content = input.getDesc("content", "");
            Integer category = input.getInt("category", 0);
            Integer level = input.getInt("level", 0);
            Integer is_comment = input.getInt("is_comment", 0);
            String author = input.getDesc("author", "");
            String receiver = input.getDesc("receiver", "");
            String imgJson = input.getDesc("img", "");
            String attachment = input.getDesc("attachment", "");
            Integer operator_id = input.getInt("operator_id", 0);
            String operator_name = input.getDesc("operator_name", "");
            String from = input.getDesc ("from", "");
            receiver = new String(Base64.getDecoder().decode(receiver),StandardCharsets.UTF_8);
            attachment = new String(Base64.getDecoder().decode(attachment),StandardCharsets.UTF_8);
            imgJson = new String(Base64.getDecoder().decode(imgJson),StandardCharsets.UTF_8);
            String updateContent = new String(Base64.getDecoder().decode(content),StandardCharsets.UTF_8);
            updateContent = replacePicture(updateContent);
            final HospitalNotice hospitalNotice = new HospitalNotice();
            hospitalNotice.setTitle(title);
            hospitalNotice.setContent(Base64.getEncoder().encodeToString(updateContent.getBytes("utf-8")));
            hospitalNotice.setCategory(category);
            hospitalNotice.setLevel(level);
            hospitalNotice.setAuthor(author);
            hospitalNotice.setReceiver(receiver);
            hospitalNotice.setImg(imgJson);
            hospitalNotice.setAttachment(attachment);
            hospitalNotice.setOperatorId(operator_id);
            hospitalNotice.setOperatorName(operator_name);
            hospitalNotice.setFromClient(from);
            hospitalNotice.setIsComment(is_comment);
            hospitalNotice.setHospital(hospital);
            final Integer nid = (Integer) DBTools.db("basedb").addItem(hospitalNotice);
            if (null == nid) {
                msg.setErrcodeAndErrmsg(30041, "通知添加失败");
                return msg;
            }
            final Integer hospitalCode = input.getInt("hospital", 999);
            final Map receiverMap = JSONUtil.fromJson(receiver, new TypeReference<Map>() {});
            final List<String> uidList = addFeedBack(receiverMap, hospitalCode, nid);
            if (uidList.size() == 0) {
                msg.setErrcodeAndErrmsg(30041, "无接收人员，请核实人员");
                return msg;
            }
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 小米推送Android代码
                    pushAndroidXiaomi(uidList, hospitalNotice);
                    // iOS推送 代码
                    push(true, uidList, hospitalNotice, "iOS");
                }
            });
            thread.start();
            return msg;
        }

        /**
         *
         * @param receiverMap  接收人数据
         * @param hospital     医院CODE
         * @param nid          通知ID   判断科室为-1的情况  返回所有接收人ID
         */
        private List<String> addFeedBack (Map receiverMap, Integer hospital, Integer nid) {
            List<Map> users = (List<Map>) receiverMap.get("user");
            List<Map> depts = (List<Map>) receiverMap.get("dept");
            List<Map> labels = (List<Map>) receiverMap.get("label");
            Set<Integer> userSet = new HashSet<Integer>();
            StringBuffer deptSb = new StringBuffer("-999,");
            for(Map deptMap : depts) {
                Integer deptId = Tools.getInt(deptMap.get("id") + "");
                if (deptId.equals(-1)) {
                    List<String> userIdList = QBuilder.db("basedb").select("concat(id, '')").from("hospital_user")
                                               .where(new Where("hospital = ", hospital).and("status = ", STATUS_ENABLE)).query()
                                               .getResultObj();
                    List<HospitalNoticeFeedback> feedbackList = new ArrayList<HospitalNoticeFeedback>();
                    for(String userId : userIdList) {
                        HospitalNoticeFeedback hospitalNoticeFeedback = new HospitalNoticeFeedback();
                        hospitalNoticeFeedback.setHospital(hospital);
                        hospitalNoticeFeedback.setNoticeId(nid);
                        hospitalNoticeFeedback.setUserId(Tools.getInt(userId, 0));
                        hospitalNoticeFeedback.setStatus(1);
                        feedbackList.add(hospitalNoticeFeedback);
                    }
                    // 插入反馈数据
                    DBTools.db("basedb").addItem(feedbackList);
                    return userIdList;
                }
                deptSb.append(deptId).append(",");
            }
            for(Map userMap : users) {
                Integer uid = Tools.getInt(userMap.get("id") + "", 0);
                userSet.add(uid);
            }
            StringBuffer laberSb = new StringBuffer("-999,");
            for(Map labelMap : labels) {
                Integer labelId = Tools.getInt(labelMap.get("id") + "", 0);
                laberSb.append(labelId).append(",");
            }
            String laberString = laberSb.toString().substring(0, (laberSb.toString().length() - 1));
            List<Map> labelList = QBuilder.db("basedb").select("new map(hlm.member_id as member_id, hlm.type as type) ").from("hospital_label_member as hlm").
                    where(new Where("hlm.label_id  in (" + laberString + ")").and("hlm.status = ", STATUS_ENABLE)).query().getResultObj();
            for(Map labelMap : labelList) {
                Integer type = Tools.getInt(labelMap.get("type") + "", 0);
                Integer member_id = Tools.getInt(labelMap.get("member_id") + "", 0);
                if (type.equals(1)) {
                    userSet.add(member_id);
                } else if (type.equals(2)) {
                    deptSb.append(member_id).append(",");
                }
            }
            String deptString = deptSb.toString().substring(0, (deptSb.toString()).length() - 1);
            List<Map> deptUserList = QBuilder.db("basedb").select("new map(hdu.user_id as id) ").from("hospital_dept_user as hdu").
                    where(new Where("hdu.dept_id in (" + deptString + ")").and("hdu.status = " + STATUS_ENABLE)).query().getResultObj();
            for(Map deptUserMap : deptUserList) {
                Integer uid = Tools.getInt(deptUserMap.get("id") + "", 0);
                userSet.add(uid);
            }
            List<HospitalNoticeFeedback> feedbackList = new ArrayList<HospitalNoticeFeedback>();
            List<String> uIdList = new ArrayList<>();
            for(Integer setId : userSet) {
                HospitalNoticeFeedback hospitalNoticeFeedback = new HospitalNoticeFeedback();
                hospitalNoticeFeedback.setHospital(hospital);
                hospitalNoticeFeedback.setNoticeId(nid);
                hospitalNoticeFeedback.setUserId(setId);
                hospitalNoticeFeedback.setStatus(1);
                feedbackList.add(hospitalNoticeFeedback);
                uIdList.add(setId + "");
            }
            // 插入反馈数据
            DBTools.db("basedb").addItem(feedbackList);
            return uIdList;
        }

        /**
         *
         * @param input  id
         * @return
         */
        public Message pushAgain(Input input) throws Exception {
            Message msg = new Message();
            Integer id = input.getInt("id", 0);
            Integer hospital = input.getInt("hospital", 999);
            List<HospitalNotice> hospitalNoticeList = QBuilder.db("basedb").queryHql("from HospitalNotice where id = " + id);
            if (hospitalNoticeList.size() == 0) {
                msg.setErrcodeAndErrmsg(30041, "消息丢失，请查看消息");
                return msg;
            }
            List<String> idList = QBuilder.db("basedb").queryHql("select concat(userId, '') from HospitalNoticeFeedback where noticeId = " + id + "and readTime is null");
            // 所有未反馈人员名单  采取重发机制
            HospitalNotice hospitalNotice = hospitalNoticeList.get(0);
            // 小米推送代码
            pushAndroidXiaomi(idList, hospitalNotice);
            // iOS推送代码
            push(true, idList, hospitalNotice, "iOS");
            return msg;
        }

    /**
     *
     * @param uidList
     * @param hospitalNotice
     * @return
     * @throws Exception
     */
    private void pushAndroidXiaomi(List<String> uidList, HospitalNotice hospitalNotice){
        Constants.useOfficial();
        Sender sender = new Sender(APP_SECRET_KEY);
        String messagePayload = hospitalNotice.getTitle();
        String title = "您有一条新消息";
        String description = hospitalNotice.getTitle();
        uidList.add("345");
        com.xiaomi.xmpush.server.Message message = new com.xiaomi.xmpush.server.Message.Builder()
                .title(title)
                .description(description).payload(messagePayload)
                .restrictedPackageName(PACKAGE_NAME)
                .notifyType(1)     // 使用默认提示音提示
                .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_ACTIVITY)
                .timeToLive(1 * 24 * 60 * 60 * 1000)
                .extra(Constants.EXTRA_PARAM_INTENT_URI,
                        "intent:#Intent;component=com.tianxiabuyi.hospital/.message.activity.MessageDetailActivity;S.id=" + hospitalNotice.getId() + ";end")
                .build();
        // 发送
        Result result = null;
        int pushNumber = 0;
        while(true && pushNumber <= 5) {
            try {
                result = sender.sendToUserAccount(message, uidList, uidList.size() + 1); //根据accountList, 发送消息到指定设备上
                break;
            } catch (IOException e1) {
                pushNumber++;
            } catch (org.json.simple.parser.ParseException e1) {
                pushNumber++;
            }
        }
    }

    // 上传图片到文件服务器
    public  String uploadFile(String path) {
        File file = new File(path);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://61.155.178.211/pu/upload.php");
        post.addHeader("Host", "cloud.eeesys.com");
        StringBody s = null;
        try {
            s = new StringBody("multi");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        FileBody fileBody = new FileBody(file);
        MultipartEntity builder = new MultipartEntity();
        builder.addPart("file[]", fileBody);
        builder.addPart("act", s);
        HttpResponse response = null;
        String json = null;
        try {
            post.setEntity(builder);
            response = client.execute(post);
            json = EntityUtils.toString(response.getEntity());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     *
     * @param content
     * @return
     */
    public String replacePicture(String content) {
        File f = new File(this.getClass().getResource("/").getPath());
        String fileNamePath = f.getAbsolutePath();
        fileNamePath = fileNamePath.substring(0, fileNamePath.indexOf("\\WEB-INF"));
        org.jsoup.nodes.Document doc = Jsoup.parse(content);
        Entities.EscapeMode.base.getMap().clear();
        Elements elements= doc.getElementsByTag("img");
        for (org.jsoup.nodes.Element element : elements) {
            String name = element.attr("src");
            if (name.indexOf("/UEditor/jsp/upload") >= 0) {
                String realFileName = fileNamePath + name;
                String uploadFileJson = uploadFile(realFileName);
                Map uploadMap = JSONUtil.mapFromJson(uploadFileJson);
                if (null == uploadMap) {
                    continue;
                }
                String uploadFileUrl = Tools.getDesc(uploadMap.get("result") + "", "http://file.eeesys.com/attach/1486359371goodmorning.png").replace("[", "").replace("]", "");
                uploadFileUrl = uploadFileUrl.replaceAll("\"", "");
                element.attr("src", uploadFileUrl);
                File delteFile = new File(realFileName);
                if (delteFile.exists()) {
                    delteFile.delete();
                }
            }
        }
        return doc.toString();
    }

    /**
     * 根据uid列表获取deviceToken列表
     * @param uidList
     * @return
     */
    public List<String> getDeviceToken(List<String> uidList) {
        if (Objects.isNull(uidList) || uidList.size() == 0)
            return null;
        StringBuilder builder = new StringBuilder();
        for (String uid:uidList) {
            builder.append(uid);
            builder.append(",");
        }
        List<Map<String, String>> uidTokenList = QBuilder.db("basedb").select("new map(concat(u.id, '') as id, d.token as token)").from("HospitalDeviceToken d, HospitalUser u").where(new Where("u.id in (" + builder.substring(0, builder.length() - 1) + ")").and("d.uid=u.id").and("u.status=", ConstantUtil.STATUS_ENABLE).and("d.status=", ConstantUtil.STATUS_ENABLE)).order("d.mTime", QBuilder.desc).query().getResultObj();
        return new ArrayList<String>(remove(uidTokenList));
    }


    /**
     * 去除重复的用户，重复的token
     * @param list
     * @return
     */
    public Set<String> remove(List<Map<String, String>> list) {
        if (Objects.isNull(list) || list.size() == 0)
            return Collections.EMPTY_SET;
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> temp = list.get(i);
            String id = temp.get("id");
            if (map.get(id) == null)
                map.put(id, temp.get("token"));
        }
        return new HashSet<String>(map.values());
    }


    /**
     * 推送
     * @param isDev false表示上线版本，true表示测试版本
     * @param uidList
     * @param hospitalNotice
     * @param type
     */
    public void push(final boolean isDev, final List<String> uidList, final HospitalNotice hospitalNotice, String type) {
        if (Objects.isNull(uidList) || Objects.isNull(hospitalNotice) || uidList.size() == 0)
            return;
        //推送时避免推送给自己
        if ("app".equals(hospitalNotice.getFromClient()))
            uidList.remove(hospitalNotice.getOperatorId() + "");
        if ("All".equals(type) || "iOS".equals(type)) {
            Thread iOSPushThread = new Thread(){
                @Override
                public void run() {
                    List<String> tokenList = getDeviceToken(uidList);
                    if (Objects.nonNull(tokenList) && tokenList.size() > 0) {
                        HashMap<String, Object> param = new HashMap<String, Object>();
                        param.put("hospital", "");
                        param.put("app_type", "hospital");
                        param.put("tokens", tokenList);
                        param.put("alert", "您有一条新消息\n"+hospitalNotice.getTitle());
                        param.put("id", hospitalNotice.getId());
                        if (isDev)
                            PushUtil.pushDev(param);
                        else
                            PushUtil.push(param);
                    }
                }
            };
            iOSPushThread.start();
        }
        if ("All".equals(type) || "Android".equals(type)) {
            Thread androidPushThread = new Thread(){
                @Override
                public void run() {
                    Constants.useOfficial();
                    Sender sender = new Sender(APP_SECRET_KEY);
                    String messagePayload = hospitalNotice.getTitle();
                    String title = hospitalNotice.getTitle();
                    String description = hospitalNotice.getTitle();
                    com.xiaomi.xmpush.server.Message message = new com.xiaomi.xmpush.server.Message.Builder()
                            .title(title)
                            .description(description).payload(messagePayload)
                            .restrictedPackageName(PACKAGE_NAME)
                            .notifyType(1)     // 使用默认提示音提示
                            .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_ACTIVITY)
                            .timeToLive(1 * 24 * 60 * 60 * 1000)
                            .extra(Constants.EXTRA_PARAM_INTENT_URI,
                                    "intent:#Intent;component=com.tianxiabuyi.hospital/.message.activity.MessageDetailActivity;S.id=" + hospitalNotice.getId() + ";end")
                            .build();
                    // 发送
                    Result result = null;
                    int pushNumber = 0;
                    while(true && pushNumber <= 5) {
                        try {
                            result = sender.sendToUserAccount(message, uidList, uidList.size() + 1); //根据accountList, 发送消息到指定设备上
                            break;
                        } catch (IOException e1) {
                            pushNumber ++;
                        } catch (org.json.simple.parser.ParseException e1) {
                            pushNumber ++;
                        }
                    }
                }
            };
            androidPushThread.start();
        }
    }
%>
